package email

import (
	"errors"
	"gitee.com/baal1990/gitee.com/baal1990/pkg/file"
	"gopkg.in/gomail.v2"
)

var (
	MailHost string
	MailPort int
	MailUser string
	MailPwd  string
)

func Init(smtpAddr string, smtpPort int, user string, pwd string) error {
	if smtpAddr == "" || user == "" || pwd == "" {
		return errors.New("mail setting info missing")
	}
	MailHost = smtpAddr
	MailPort = smtpPort
	MailUser = user
	MailPwd = pwd
	return nil
}

//目标地址
func SendGoMail(mailAddress []string, filename string, title string, body string) error {
	if filename != "" {
		if !file.FileExists(filename) {
			return errors.New("No find attach file:")
		}
	}
	if len(mailAddress) <= 0 {
		return errors.New("Unspecified email address")
	}

	m := gomail.NewMessage()
	// 这种方式可以添加别名，即 nickname， 也可以直接用<code>m.SetHeader("From", MAIL_USER)</code>
	nickname := "DCE400"
	m.SetHeader("From", nickname+"<"+MailUser+">")
	// 发送给多个用户
	m.SetHeader("To", mailAddress...)
	// 设置邮件主题
	m.SetHeader("Subject", title)

	// 设置邮件正文
	m.SetBody("text/html", body)
	if filename != "" {
		m.Attach(filename)
	}

	d := gomail.NewDialer(MailHost, MailPort, MailUser, MailPwd)
	d.SSL = true
	//关闭认证
	//d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	// 发送邮件
	err := d.DialAndSend(m)
	return err
}
